<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <!-- //按钮区域 -->
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 权限列表数据显示 -->
    <!-- 不包裹el-card无法显示权限列表数据,不知道为什么. -->
    <el-card class="card-table">
      <el-table :data="RoleList" border stripe slot-scope="scope">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbuttom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限渲染 -->
              <el-col :span="5">
                <el-tag closable @close="closeByid(scope.row, item1.id)">
                  {{
                  item1.authName
                  }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限渲染 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="i2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="closeByid(scope.row, item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限渲染 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="i3.id"
                      closable
                      @close="closeByid(scope.row, item3.id)"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRoleDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑用户弹窗 -->
    <el-dialog title="修改权限信息" :visible.sync="editDialogVisible" width="50%" @close="editClose">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限dialog -->
    <el-dialog title="分配权限" :visible.sync="roleDialogVisible" width="50%" @close="clearRights">
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "Roles",
  data() {
    return {
      RoleList: [],
      // 编辑信息弹窗
      editDialogVisible: false,
      // 分配权限dialog
      roleDialogVisible: false,
      //保存编辑信息
      editForm: {
        roleId: "",
        roleName: "",
        roleDesc: "",
      },
      //保存分配权限信息
      rightsList: [],
      // 树形空间绑定的数据源
      treeProps: {
        children: "children",
        label: "authName",
      },
      //树形结构默认选中的key值
      defKeys: [],
      // 保存角色id
      roleid: "",
      //修改角色验证规则
      editFormRules: {
        roleDesc: [
          { required: true, message: "请输角色描述!", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 获取角色列表数据
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status == 200) {
        this.RoleList = res.data;
      } else {
        this.$message.error("请求数据失败!");
      }
    },
    // 显示编辑信息弹窗
    async showEditDialog(id) {
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status == 200) {
        this.editForm = res.data;
        // console.log(this.editForm);
      } else {
        return;
      }
    },
    //监听修改用户框,关闭时间
    editClose() {
      this.$refs.editFormRef.resetFields();
    },
    //用户确定编辑时发生
    EditRolesInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            "roles/" + this.editForm.roleId,
            {
              roleName: this.editForm.roleName,
              roleDesc: this.editForm.roleDesc,
            }
          );
          if (res.meta.status == 200) {
            //将消息框关闭
            this.editDialogVisible = false;
            // 刷新用户
            this.getRoleList();
            // 提示信息
            this.$message.success("修改角色成功!");
          } else {
            this.$message.error("修改角色失败!");
          }
        }
      });
    },
    // 根据id删除用户信息
    async deleteRoles(id) {
      const confirmRlust = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmRlust);
      //如果用户点了确定泽返回字符串confirm,选择了取消返回字符串cancel
      if (confirmRlust === "confirm") {
        const { data: res } = await this.$http.delete("roles/" + id);
        if (res.meta.status == 200) {
          this.$message.success("删除角色成功!");
          this.getRoleList();
        } else {
          this.$message.error("删除角色失败!");
          this.getRoleList();
        }
      } else {
        this.$message.info("取消了删除!");
      }
    },
    //根据id删除权限
    async closeByid(role, id) {
      const confirmRlust = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmRlust);
      //如果用户点了确定泽返回字符串confirm,选择了取消返回字符串cancel
      if (confirmRlust === "confirm") {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${id}`
        );
        if (res.meta.status == 200) {
          this.$message.success("删除权限成功!");
        } else {
          this.$message.error("删除权限失败!");
          console.log(res.meta.msg);
        }
        role.children = res.data;
      } else {
        this.$message.info("取消了删除!");
      }
    },
    // 显示分配权限dialog
    async showRoleDialog(role) {
      this.roleid = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status == 200) {
        this.rightsList = res.data;
      }
      this.saveKyes(role, this.defKeys);
      this.roleDialogVisible = true;
    },
    //递归获取当前角色拥有的三级权限并且保存到defKyes中
    saveKyes(role, arr) {
      if (!role.children) {
        arr.push(role.id);
      } else {
        role.children.forEach((item) => {
          this.saveKyes(item, arr);
        });
      }
    },
    // 每次关闭窗口清空选择的权限
    clearRights() {
      this.defKeys = [];
    },
    // 保存已经选中的权限
    async allRights() {
      const Keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = Keys.join(",");
      console.log(Keys);
      const { data: res } = await this.$http.post(
        `roles/${this.roleid}/rights`,
        {
          rids: idStr,
        }
      );
      if (res.meta.status == 200) {
        this.$message.success("分配权限成功！");
        this.getRoleList();
        this.roleDialogVisible = false;
      } else {
        this.$message.error("分配权限失败！");
      }
    },
  },
  created() {
    this.getRoleList();
  },
  components: {},
  computed: {},
  beforeMount() {},
  mounted() {},
  watch: {},
};
</script>
<style lang="less" scoped>
.card-table {
  margin-top: 10px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eeeeee;
}
.bdbuttom {
  border-bottom: 1px solid #eeeeee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
